import { HTMLCanvasElement } from '../types';
import { CollisionManager } from '../physics/CollisionManager';
import { ResourceManager } from '../resources/ResourceManager';
import { AudioManager } from '../audio/AudioManager';

/**
 * 游戏选项
 */
export interface GameOptions {
    canvas: HTMLCanvasElement;
    width: number;
    height: number;
    backgroundColor?: string;
}

/**
 * 游戏类
 */
export class Game {
    readonly canvas: HTMLCanvasElement;
    readonly ctx: CanvasRenderingContext2D;
    readonly width: number;
    readonly height: number;
    readonly backgroundColor: string;
    
    readonly resourceManager: ResourceManager;
    readonly audioManager: AudioManager;
    readonly collisionManager: CollisionManager;
    
    private isRunning: boolean = false;
    private lastTime: number = 0;
    
    constructor(options: GameOptions) {
        this.canvas = options.canvas;
        this.ctx = this.canvas.getContext('2d')!;
        this.width = options.width;
        this.height = options.height;
        this.backgroundColor = options.backgroundColor || '#000000';
        
        // 初始化核心系统
        this.resourceManager = new ResourceManager();
        this.audioManager = new AudioManager();
        this.collisionManager = new CollisionManager();
        
        // 设置画布大小
        this.resize();
    }
    
    /**
     * 启动游戏
     */
    start(update: (deltaTime: number) => void, render: () => void): void {
        if (this.isRunning) return;
        
        this.isRunning = true;
        this.lastTime = performance.now();
        
        const gameLoop = (currentTime: number) => {
            if (!this.isRunning) return;
            
            const deltaTime = (currentTime - this.lastTime) / 1000;
            this.lastTime = currentTime;
            
            // 更新游戏状态
            update(deltaTime);
            
            // 渲染游戏画面
            render();
            
            // 继续下一帧
            requestAnimationFrame(gameLoop);
        };
        
        requestAnimationFrame(gameLoop);
    }
    
    /**
     * 停止游戏
     */
    stop(): void {
        this.isRunning = false;
    }
    
    /**
     * 调整画布大小
     */
    resize(): void {
        this.canvas.width = this.width;
        this.canvas.height = this.height;
    }
    
    /**
     * 清理资源
     */
    destroy(): void {
        this.stop();
        this.resourceManager.destroy();
        this.audioManager.destroy();
        this.collisionManager.destroy();
    }
} 